package cn.com.heaton.bleLib.logic;

import java.util.UUID;

public class Rc4 {

    public static byte[] RC4Key = {(byte) 0xFC, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01, (byte) 0xFC, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01};

    public static byte[] encry_RC4_byte(byte[] b_data, byte[] key) {
        if (b_data == null || key == null) {
            return null;
        }
        return RC4Base(b_data, key);
    }

    private static byte[] initKey(byte[] b_key) {
        byte state[] = new byte[256];

        for (int i = 0; i < 256; i++) {
            state[i] = (byte) i;
        }
        int index1 = 0;
        int index2 = 0;
        if (b_key == null || b_key.length == 0) {
            return null;
        }
        for (int i = 0; i < 256; i++) {
            index2 = ((b_key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
            byte tmp = state[i];
            state[i] = state[index2];
            state[index2] = tmp;
            index1 = (index1 + 1) % b_key.length;
        }
        return state;
    }

    public static byte[] RC4Base(byte[] input, byte[] keyBytes) {
        int x = 0;
        int y = 0;
        byte key[] = initKey(keyBytes);
        int xorIndex;
        byte[] result = new byte[input.length];

        for (int i = 0; i < input.length; i++) {
            x = (x + 1) & 0xff;
            y = ((key[x] & 0xff) + y) & 0xff;
            byte tmp = key[x];
            key[x] = key[y];
            key[y] = tmp;
            xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
            result[i] = (byte) (input[i] ^ key[xorIndex]);
        }
        return result;
    }

    public static void main(String[] args) {

        //06e400040808
        byte[] Key = {(byte) 0xFC, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01, (byte) 0xFC, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01};
        byte[] data = new byte[]{0x06, (byte) 0xe4, 0x00, 0x04, 0x08, 0x08};
        System.out.println(">>>" + HexUtil.encodeHexStr(data));
        byte[] result = encry_RC4_byte(data, Key);
        System.out.println(">>>" + HexUtil.encodeHexStr(result));

        // System.out.println(decry_RC4(str, UUID.randomUUID().toString().toUpperCase()));
    }

}
